package com.ruoyi.system.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.ruoyi.business.service.impl.BaseServiceImpl;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysDictType;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.BusinessStatus;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.AddressUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.domain.SysOperLog;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysDictTypeService;
import com.ruoyi.system.service.ISysOperLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.business.mapper.IndicatorMapper;
import com.ruoyi.business.domain.Indicator;
import com.ruoyi.system.service.IIndicatorService;

/**
 * 用于存储评价指标及其详细信息Service业务层处理
 * 
 * @author song
 * @date 2024-11-24
 */
@Service
public class IndicatorServiceImpl implements IIndicatorService
{
    @Autowired
    private IndicatorMapper indicatorMapper;

    @Autowired
    private ISysDictDataService dictDataService;

    @Autowired
    private ISysDictTypeService dictTypeService;

    /**
     * 查询用于存储评价指标及其详细信息
     * 
     * @param id 用于存储评价指标及其详细信息主键
     * @return 用于存储评价指标及其详细信息
     */
    @Override
    public Indicator selectIndicatorById(Long id)
    {
        Indicator indicator = indicatorMapper.selectIndicatorById(id);

        //184
        //185
        //186
        //187
        //188
        //189
        if(indicator.getEvaluationMetric() == "184" || indicator.getEvaluationMetric() == "185" || indicator.getEvaluationMetric() == "186" || indicator.getEvaluationMetric() == "187" || indicator.getEvaluationMetric() == "188" || indicator.getEvaluationMetric() == "189"){
            indicator.setEditName(true);
        }
        
        return indicatorMapper.selectIndicatorById(id);
    }

    /**
     * 查询用于存储评价指标及其详细信息列表
     * 
     * @param indicator 用于存储评价指标及其详细信息
     * @return 用于存储评价指标及其详细信息
     */
    @Override
    public ArrayList<Indicator> selectIndicatorList(Indicator indicator)
    {
        if(!indicator.getType().equals("-1")){
            if("1".equals(indicator.getType())){
                indicator.setType("102");
            }else {
                indicator.setType("103");
            }
        }else {
            indicator.setType(null);
        }

        return indicatorMapper.selectIndicatorList(indicator);
    }

    /**
     * 新增用于存储评价指标及其详细信息
     * 
     * @param indicator 用于存储评价指标及其详细信息
     * @return 结果
     */
    @Override
    public int insertIndicator(Indicator indicator)
    {

        SysDictData sysDictData = dictDataService.selectDictDataById(Long.parseLong(indicator.getEvaluationMetric()));


        //设置权重
        sysDictData.setDictValue(indicator.getWeight().toString());
        dictDataService.updateDictData(sysDictData);

        // 获取类型
        String dictType = sysDictData.getRemark();
        SysDictType sysDictType = dictTypeService.selectDictTypeById(Long.parseLong(dictType));
        sysDictType.setRemark(indicator.getAssessmentDetails());
        dictTypeService.updateDictType(sysDictType);

        // 定义模板中的占位符及其对应的正则表达式
        String template = sysDictType.getDataTemplate();

        List<Long> placeholders = extractPlaceholders(template);

        String patternStr = template.replaceAll("\\$\\{\\d+\\}", "(\\\\d+?)").replaceAll("\\$\\{weight\\}", indicator.getWeight().toString());
        System.out.println(patternStr);
        // 使用正则表达式匹配输入字符串中的数值
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(indicator.getScoringCriteria());

        // 获取模版数据
        List<SysDictData> datas = dictTypeService.selectDictDataByType(sysDictType.getDictType());
        Map<Long, String> result = new HashMap<>();

        while (matcher.find()) {
            for (int i = 1; i <= matcher.groupCount(); i++) {
                String group = matcher.group(i);
                System.out.println("group is ..."+group);

                if (i <= placeholders.size()) {
                    result.put(placeholders.get(i - 1), group);
                    System.out.println("sort is ..."+placeholders.get(i - 1)+"value is .."+group);
                }
            }
        }

        for (SysDictData data : datas) {

            data.setDictValue(result.get(data.getDictSort()));
            dictDataService.updateDictData(data);

            if(null != data.getRemark() && data.getRemark().equals("weight")){
                data.setDictValue(indicator.getWeight().toString());
                dictDataService.updateDictData(data);
            }
        }

        indicator.setCreateTime(DateUtils.getNowDate());

        // 获取当前的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();

        // *========数据库日志=========*//
        SysOperLog operLog = new SysOperLog();
        operLog.setTitle("积分规则");
        operLog.setStatus(BusinessStatus.SUCCESS.ordinal());
        // 请求的地址
        String ip = IpUtils.getIpAddr();
        operLog.setOperIp(ip);
        operLog.setOperUrl(StringUtils.substring(ServletUtils.getRequest().getRequestURI(), 0, 255));
        if (loginUser != null)
        {
            operLog.setOperName(loginUser.getUsername());
            SysUser currentUser = loginUser.getUser();
            if (StringUtils.isNotNull(currentUser) && StringUtils.isNotNull(currentUser.getDept()))
            {
                operLog.setDeptName(currentUser.getDept().getDeptName());
            }
        }
        // 设置方法名称
        operLog.setMethod("edit");
        // 设置请求方式
        operLog.setRequestMethod(ServletUtils.getRequest().getMethod());

        // 处理设置注解上的参数
        String templateOpt = String.format("积分规则 ，增加，%s，%s",
                sysDictData.getDictLabel(),indicator.getScoringCriteria()
        );
        operLog.setJsonResult(templateOpt);
        // 设置消耗时间
        operLog.setCostTime(0L);

        operLog.setOperLocation(AddressUtils.getRealAddressByIP(operLog.getOperIp()));
        SpringUtils.getBean(ISysOperLogService.class).insertOperlog(operLog);

        return indicatorMapper.insertIndicator(indicator);
    }


    public static List<Long> extractPlaceholders(String template) {
        // 定义正则表达式，用于匹配 ${} 占位符中的数字
        Pattern pattern = Pattern.compile("\\$\\{(\\d+)\\}");
        Matcher matcher = pattern.matcher(template);

        // 创建一个列表来存储提取的数字
        List<Long> placeholders = new ArrayList<>();

        // 查找所有匹配项，并将提取的数字添加到列表中
        while (matcher.find()) {
            Long number = Long.parseLong(matcher.group(1));
            placeholders.add(number);

            System.out.println("占位符索引....."+number);
        }

        return placeholders;
    }


    @Override
    public boolean checkIndicatorNameUnique(Indicator indicator) {

        //evaluation_metric
        Indicator ind = indicatorMapper.checkIndicatorNameUnique(indicator.getEvaluationMetric());
        if(ind!=null){return true;}else {return false;}
    }

    @Override
    public int getAllWeight(Indicator indicator) {

        Map<String,Object> maps = indicatorMapper.getAllWeight(indicator.getEvaluationMetric());

        if(null == maps || maps.isEmpty()){return 0;}

        if(!maps.containsKey("sumWeight") || maps.get("sumWeight") == null){return 0;}

        BigDecimal allWeight = (BigDecimal)maps.get("sumWeight");
        return allWeight.intValue();
    }

    /**
     * 修改用于存储评价指标及其详细信息
     * 
     * @param indicator 用于存储评价指标及其详细信息
     * @return 结果
     */
    @Override
    public int updateIndicator(Indicator indicator)
    {
        SysDictData sysDictData = dictDataService.selectDictDataById(Long.parseLong(indicator.getEvaluationMetric()));
        String oldTitle = sysDictData.getDictLabel();

        if(indicator.isEditName()){
            sysDictData.setDictLabel(indicator.getEvaluationMetricName());
        }

        String newTitle = sysDictData.getDictLabel();
        //设置权重
        sysDictData.setDictValue(indicator.getWeight().toString());
        dictDataService.updateDictData(sysDictData);

        // 获取类型
        String dictType = sysDictData.getRemark();
        SysDictType sysDictType = dictTypeService.selectDictTypeById(Long.parseLong(dictType));
        sysDictType.setRemark(indicator.getAssessmentDetails());
        dictTypeService.updateDictType(sysDictType);

        // 定义模板中的占位符及其对应的正则表达式
        String template = sysDictType.getDataTemplate();

        List<Long> placeholders = extractPlaceholders(template);

        String patternStr = template.replaceAll("\\$\\{\\d+\\}", "(\\\\d+?)").replaceAll("\\$\\{weight\\}", indicator.getWeight().toString());
        System.out.println(patternStr);
        // 使用正则表达式匹配输入字符串中的数值
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(indicator.getScoringCriteria());

        // 获取模版数据
        List<SysDictData> datas = dictTypeService.selectDictDataByType(sysDictType.getDictType());
        Map<Long, String> result = new HashMap<>();

        while (matcher.find()) {
            for (int i = 1; i <= matcher.groupCount(); i++) {
                String group = matcher.group(i);
                System.out.println("group is ..."+group);

                if (i <= placeholders.size()) {
                    result.put(placeholders.get(i - 1), group);
                    System.out.println("sort is ..."+placeholders.get(i - 1)+"value is .."+group);
                }
            }
        }


        for (SysDictData data : datas) {

            data.setDictValue(result.get(data.getDictSort()));
            dictDataService.updateDictData(data);

            if(null != data.getRemark() && data.getRemark().equals("weight")){
                data.setDictValue(indicator.getWeight().toString());
                dictDataService.updateDictData(data);
            }
        }

        indicator.setUpdateTime(DateUtils.getNowDate());

        // 获取当前的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();

        // *========数据库日志=========*//
        SysOperLog operLog = new SysOperLog();
        operLog.setTitle("积分规则");
        operLog.setStatus(BusinessStatus.SUCCESS.ordinal());
        // 请求的地址
        String ip = IpUtils.getIpAddr();
        operLog.setOperIp(ip);
        operLog.setOperUrl(StringUtils.substring(ServletUtils.getRequest().getRequestURI(), 0, 255));
        if (loginUser != null)
        {
            operLog.setOperName(loginUser.getUsername());
            SysUser currentUser = loginUser.getUser();
            if (StringUtils.isNotNull(currentUser) && StringUtils.isNotNull(currentUser.getDept()))
            {
                operLog.setDeptName(currentUser.getDept().getDeptName());
            }
        }
        // 设置方法名称
        operLog.setMethod("edit");
        // 设置请求方式
        operLog.setRequestMethod(ServletUtils.getRequest().getMethod());

        Indicator old = indicatorMapper.selectIndicatorById(indicator.getId());
        // 处理设置注解上的参数
        String templateOpt = String.format("积分规则 ，%s，%s， 修改%s，%s",
                oldTitle, old.getScoringCriteria(),newTitle,indicator.getScoringCriteria()
        );
        operLog.setJsonResult(templateOpt);
        // 设置消耗时间
        operLog.setCostTime(0L);

        operLog.setOperLocation(AddressUtils.getRealAddressByIP(operLog.getOperIp()));
        SpringUtils.getBean(ISysOperLogService.class).insertOperlog(operLog);

        return indicatorMapper.updateIndicator(indicator);
    }

    /**
     * 批量删除用于存储评价指标及其详细信息
     * 
     * @param ids 需要删除的用于存储评价指标及其详细信息主键
     * @return 结果
     */
    @Override
    public int deleteIndicatorByIds(Long[] ids)
    {
        for(Long id : ids){
            Indicator indicator = indicatorMapper.selectIndicatorById(id);
            SysDictData sysDictData = dictDataService.selectDictDataById(Long.parseLong(indicator.getEvaluationMetric()));

            // 获取当前的用户
            LoginUser loginUser = SecurityUtils.getLoginUser();

            // *========数据库日志=========*//
            SysOperLog operLog = new SysOperLog();
            operLog.setTitle("积分规则");
            operLog.setStatus(BusinessStatus.SUCCESS.ordinal());
            // 请求的地址
            String ip = IpUtils.getIpAddr();
            operLog.setOperIp(ip);
            operLog.setOperUrl(StringUtils.substring(ServletUtils.getRequest().getRequestURI(), 0, 255));
            if (loginUser != null)
            {
                operLog.setOperName(loginUser.getUsername());
                SysUser currentUser = loginUser.getUser();
                if (StringUtils.isNotNull(currentUser) && StringUtils.isNotNull(currentUser.getDept()))
                {
                    operLog.setDeptName(currentUser.getDept().getDeptName());
                }
            }
            // 设置方法名称
            operLog.setMethod("edit");
            // 设置请求方式
            operLog.setRequestMethod(ServletUtils.getRequest().getMethod());

            // 处理设置注解上的参数
            String templateOpt = String.format("积分规则 ，删除，%s，%s",
                    sysDictData.getDictLabel(),indicator.getScoringCriteria()
            );
            operLog.setJsonResult(templateOpt);
            // 设置消耗时间
            operLog.setCostTime(0L);

            operLog.setOperLocation(AddressUtils.getRealAddressByIP(operLog.getOperIp()));
            SpringUtils.getBean(ISysOperLogService.class).insertOperlog(operLog);
        }

        return indicatorMapper.deleteIndicatorByIds(ids);
    }

    /**
     * 删除用于存储评价指标及其详细信息信息
     * 
     * @param id 用于存储评价指标及其详细信息主键
     * @return 结果
     */
    @Override
    public int deleteIndicatorById(Long id)
    {
        Indicator indicator = indicatorMapper.selectIndicatorById(id);
        SysDictData sysDictData = dictDataService.selectDictDataById(Long.parseLong(indicator.getEvaluationMetric()));

        // 获取当前的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();

        // *========数据库日志=========*//
        SysOperLog operLog = new SysOperLog();
        operLog.setTitle("积分规则");
        operLog.setStatus(BusinessStatus.SUCCESS.ordinal());
        // 请求的地址
        String ip = IpUtils.getIpAddr();
        operLog.setOperIp(ip);
        operLog.setOperUrl(StringUtils.substring(ServletUtils.getRequest().getRequestURI(), 0, 255));
        if (loginUser != null)
        {
            operLog.setOperName(loginUser.getUsername());
            SysUser currentUser = loginUser.getUser();
            if (StringUtils.isNotNull(currentUser) && StringUtils.isNotNull(currentUser.getDept()))
            {
                operLog.setDeptName(currentUser.getDept().getDeptName());
            }
        }
        // 设置方法名称
        operLog.setMethod("edit");
        // 设置请求方式
        operLog.setRequestMethod(ServletUtils.getRequest().getMethod());

        // 处理设置注解上的参数
        String templateOpt = String.format("积分规则 ，删除，%s，%s",
                sysDictData.getDictLabel(),indicator.getScoringCriteria()
        );
        operLog.setJsonResult(templateOpt);
        // 设置消耗时间
        operLog.setCostTime(0L);

        operLog.setOperLocation(AddressUtils.getRealAddressByIP(operLog.getOperIp()));
        SpringUtils.getBean(ISysOperLogService.class).insertOperlog(operLog);

        return indicatorMapper.deleteIndicatorById(id);
    }

    public static void main(String[] args) {
        String template = "正高级${weight}分； 副高级${2}分；中级${3}分；初级${4}分。";

        // 替换 ${weight} 为实际值
        double weight = 25;
        String weightedTemplate = template.replace("${weight}", "(\\d+(\\.\\d+)?)");

        // 替换其他占位符为正则表达式模式
        String patternStr = weightedTemplate.replaceAll("\\$\\{\\d+\\}", "(\\\\d+?)");
        System.out.println(patternStr);

        // 使用正则表达式匹配输入字符串中的数值
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher("正高级22分； 副高级15分；中级10分；初级5分。");

        while (matcher.find()) {
            for (int i = 1; i <= matcher.groupCount(); i++) {
                System.out.println(matcher.group(i));
            }
        }
    }
}
